import React, { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { Select, Button, Table, Input, DatePicker } from "antd";
import dayjs from "dayjs";
import customParseFormat from "dayjs/plugin/customParseFormat";
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
} from "@ant-design/icons";
import { text_check, post_axios, format_time, add_zero } from "../../utils";

export default function Operation(props) {
  dayjs.extend(customParseFormat);
  const { t } = useTranslation();
  const { RangePicker } = DatePicker;
  const [tableHeight, setTableHeight] = useState(0);
  const { actions, setSpinning } = props;
  let { menu_action, user_power_lang, username, user_grade } = actions;
  user_power_lang = JSON.parse(user_power_lang);

  // 国内国外判断
  const session_company = sessionStorage.getItem("company");
  let localStorage_company = JSON.parse(localStorage.getItem("choose_company"));
  const local_company_object =
    localStorage_company &&
    localStorage_company[username] &&
    localStorage_company[username]
      ? localStorage_company[username]
      : "";

  const [log_list, setLog_list] = useState([]);
  const [page, setPage] = useState(1);
  const [rows, setRows] = useState(20);
  const [total, setTotal] = useState(0);
  // 公司范围
  const [company_scope, setCompany_scope] = useState("now");
  //操作对象
  const [op_target, setOp_target] = useState("");
  // 操作行为
  const [op_type, setOp_type] = useState("mega_op_his_login");
  // 时间

  let today_time = new Date();
  let year = today_time.getFullYear();
  let month = add_zero(today_time.getMonth() + 1);
  let day = today_time.getDate();
  const [date_stamp, setDate_stamp] = useState([
    dayjs(new Date(year, month, day, 0, 0)),
    dayjs(new Date(year, month, day, 23, 59, 59)),
  ]);
  const company_scope_list = [
    {
      label: t("system_manager.current_selected"),
      key: "now",
      value: "now",
    },
    {
      label: t("system_manager.all"),
      key: "*",
      value: "*",
    },
  ];
  const op_type_list = [
    {
      label: text_check({
        msg_cn: "登录",
        msg_en: "Login",
      }),
      value: "mega_op_his_login",
      key: "mega_op_his_login",
    },
    {
      label: text_check({
        msg_cn: "配置类",
        msg_en: "System Setting",
      }),
      value: "mega_op_his_set",
      key: "mega_op_his_set",
    },
    {
      label: text_check({
        msg_cn: "设置库存",
        msg_en: "Replenishment",
      }),
      value: "mega_op_his_stock",
      key: "mega_op_his_stock",
    },
    {
      label: text_check({
        msg_cn: "设置容量",
        msg_en: "Capacity Setting",
      }),
      value: "mega_op_his_volume",
      key: "mega_op_his_volume",
    },
    {
      label: text_check({
        msg_cn: "上下架",
        msg_en: "Product Setting",
      }),
      value: "mega_op_his_shelf",
      key: "mega_op_his_shelf",
    },
  ];

  const time_disabled = (current, partial, info) => {
    return current && current > dayjs().endOf("day");
  };

  const getData = async (newPage, newRows) => {
    let upMsg = {
      page: newPage ? newPage : page,
      rows: newRows ? newRows : rows,
      company_id: company_scope === "now" ? local_company_object.id : "",
      company: company_scope === "now" ? local_company_object.company : "",
      op_target: op_target,
      op_type: op_type,
      bdate_stamp: Math.round(new Date(date_stamp[0]).getTime() / 1000),
      edate_stamp: Math.round(new Date(date_stamp[1]).getTime() / 1000),
    };
    setSpinning(true);
    let res = await post_axios("operation_log", "m_query", upMsg);
    setSpinning(false);
    if (!res) return;
    setLog_list(res.data_rows.rows);
    setTotal(res.data_rows.total);
  };
  const op_action_bool = Boolean(session_company !== "mg");
  const company_bool = Boolean(user_grade < 10);
  const columns = [
    {
      dataIndex: "idx",
      align: "center",
      width: 40,
      render: (_, record, index) => <>{index + 1}</>,
    },
    {
      title: t("system_manager.company"),
      dataIndex: "company",
      align: "center",
      hidden: company_bool,
    },
    {
      title: t("system_manager.login_name"),
      dataIndex: "username",
      align: "center",
    },
    {
      title: t("system_manager.operation_behavior"),
      dataIndex: "op_type",
      align: "center",
    },
    {
      title: t("system_manager.action_object"),
      dataIndex: "op_target",
      align: "center",
    },
    {
      title: t("system_manager.operation_business_content"),
      dataIndex: "op_msg",
      align: "center",
      width: 500,
    },
    {
      title: t("system_manager.action"),
      dataIndex: "op_action",
      align: "center",
      hidden: op_action_bool,
    },
    {
      title: t("system_manager.request_type"),
      dataIndex: "request_type",
      align: "center",
    },
    {
      title: "IP",
      dataIndex: "ip",
      align: "center",
    },
    {
      title: t("system_manager.operation_time"),
      align: "center",
      render: (_, record) => (
        <>
          <div>{format_time(record.op_stamp, "type_s")}</div>
        </>
      ),
    },
  ];
  // 分页器
  const pageOnChange = async (page, pageSize) => {
    setPage(page);
    setRows(pageSize);
    getData(page, pageSize);
  };

  const search_data = () => {
    setPage(1);
    getData(1);
  };
  useEffect(() => {
    // 挂载后或者更新后的操作
    getData().then(() => {
      const tabBoxHeight =
        document.getElementsByClassName("operation_log")[0].scrollHeight;
      const tableHeight = tabBoxHeight - 96 - 70;
      setTableHeight(tableHeight);
    });
  }, []);
  return (
    <div className="operation_log modules">
      <div className="screen_ipt">
        <div className="ipt_box normal_title">
          <div className="ipt_box_title">{t("system_manager.company")}</div>
          <Select
            size="small"
            placeholder=" "
            options={company_scope_list}
            value={company_scope}
            onChange={(value) => setCompany_scope(value)}
          />
        </div>
        <div className="ipt_box normal_title">
          <div className="ipt_box_title">
            {t("system_manager.operation_behavior")}
          </div>
          <Select
            size="small"
            placeholder=" "
            options={op_type_list}
            value={op_type}
            onChange={(value) => setOp_type(value)}
          />
        </div>

        <div className="ipt_box normal_title">
          <div className="ipt_box_title">
            {t("system_manager.operation_object")}
          </div>
          <Input
            placeholder=" "
            value={op_target}
            size="small"
            onChange={(e) => setOp_target(e.target.value)}
          />
        </div>
        <div className="ipt_box date_title">
          <div className="ipt_box_title">{t("system_manager.time")}</div>
          <RangePicker
            size="small"
            disabledDate={time_disabled}
            onChange={(date, dateString) => {
              setDate_stamp(date);
            }}
          />
        </div>
      </div>
      <div className="screen_btn">
        <div className="btn_box">
          {/* 添加 */}
          {menu_action.indexOf("m_add") > -1 ? (
            <Button
              size="small"
              type="text"
              icon={<PlusOutlined style={{ color: "#1677FF" }} />}
            >
              {text_check(user_power_lang["m_add"])}
            </Button>
          ) : (
            ""
          )}
          {/* 修改 */}
          {menu_action.indexOf("m_modify") > -1 ? (
            <Button
              size="small"
              type="text"
              icon={<EditOutlined style={{ color: "#1677FF" }} />}
            >
              {text_check(user_power_lang["m_modify"])}
            </Button>
          ) : (
            ""
          )}
          {/* 删除 */}
          {menu_action.indexOf("m_del") > -1 ? (
            <Button
              size="small"
              type="text"
              icon={<DeleteOutlined style={{ color: "#1677FF" }} />}
            >
              {text_check(user_power_lang["m_del"])}
            </Button>
          ) : (
            ""
          )}
          {/* 查询 */}
          {menu_action.indexOf("m_query") > -1 ? (
            <Button
              size="small"
              type="text"
              icon={<SearchOutlined style={{ color: "#1677FF" }} />}
              onClick={search_data}
            >
              {text_check(user_power_lang["m_query"])}
            </Button>
          ) : (
            ""
          )}
        </div>
      </div>
      <div className="table_box">
        <div className="page-table">
          <Table
            dataSource={log_list}
            size="small"
            bordered
            columns={columns}
            rowKey="id"
            virtual
            scroll={{
              y: tableHeight,
            }}
            pagination={{
              defaultCurrent: page,
              defaultPageSize: rows,
              size: "small",
              current: page,
              total: total,
              responsive: true,
              showTotal: (total) =>
                text_check({
                  msg_cn: `共 ${total} 条`,
                  msg_en: `Total ${total} items`,
                }),
              onChange: pageOnChange,
            }}
          />
        </div>
      </div>
    </div>
  );
}
